<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { Switch, Search, Refresh, UploadFilled } from "@element-plus/icons-vue"

import { formatDateTime } from "@/utils"
import { usePagination } from "@/hooks/usePagination"
import { downLoadVarTmp, sendMsgNum, sendMsgFile } from "@/api/msg"
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

const ruleFormRef = ref<FormInstance>()
defineOptions({
  name: "Addnote"
})
//  表单内容
const ruleForm = reactive<any>({
  msgType: "custom",
  sendtime: "",
  msgSign: "",
  phone: "",
  content: ""
})
const checked1 = ref(false)
const sendType = ref("1")
//  表单验证
import { checkComma } from "@/utils/validate"
const rules = reactive<FormRules>({
  msgType: [{ required: true, message: "请选择短信类型", trigger: "change" }],
  msgSign: [
    {
      required: true,
      message: "请选择签名",
      trigger: "change"
    }
  ],
  content: [{ required: true, message: "请输入短信内容", trigger: "blur" }],
  phone: [{ required: true, validator: checkComma, trigger: "blur" }]
})

import { seeMsgSign } from "@/api/msg"
const singnList = ref<any>([])

const getSignList = () => {
  seeMsgSign({
    page: 1,
    size: 1000,
    auditResult: "2"
    // package_id: searchData.package_id
  })
    .then((res: any) => {
      singnList.value = res.data.list
    })
    .catch(() => {
      singnList.value = []
    })
}
getSignList()
//模板列表
import { seeMsgTmp } from "@/api/msg"

const dialogVisibleTmp = ref(false)
const tableTmp = ref([])
const getTableData = () => {
  seeMsgTmp({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    temName: searchData.temName,
    auditResult: 2
    // package_id: searchData.package_id
  })
    .then((res: any) => {
      paginationData.total = res.data.total
      tableTmp.value = res.data.list
      console.log(res, "查询的数据")
    })
    .catch(() => {
      tableTmp.value = []
    })
    .finally(() => {})
}

//模板选择点击
const handleChangeTmp = () => {
  dialogVisibleTmp.value = true
  getTableData()
}
//选择模板
const tpId = ref("")
const handleUpdate = (row: any) => {
  dialogVisibleTmp.value = false
  ruleForm.content = row.temContent
  tpId.value = row.temId
  if (row.temContent.indexOf("{") != -1) {
    sendType.value = "2"
  }
}
//模板搜索
const searchFormRef = ref<FormInstance | null>(null)

const searchData = reactive({
  temName: ""
})
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}

// 重置按键
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData)

//签名切换

watch([() => ruleForm.msgSign], (n: any, o: any) => {
  ruleForm.content = ruleForm.content.replace(o, n)
})
watch([() => checked1.value], (n: any) => {
  if (n[0]) {
    ruleForm.content = ruleForm.content.concat("，拒收请回复R")
  } else {
    ruleForm.content = ruleForm.content.replace("，拒收请回复R", "")
  }
})

//签名类型切换
const tmpTypeChange = () => {
  ruleForm.content = ""
  ruleForm.msgSign = ""
  ruleForm.phone = ""
  tpId.value = ""
  checked1.value = false
}
//发送方式改变
const sendTypeChange = () => {
  ruleForm.phone = ""
}
//文件上传

const fileList1 = ref<any>([])
const handleChageFile = (file: any, resfileList: any) => {
  const size = ref(300)
  console.log(resfileList)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的文件!`)
    fileList1.value = []
  } else {
    fileList1.value = resfileList
  }
}
//移除文件
const handleDelFile = () => {
  fileList1.value = []
}
//下载变量模板
const handleUploadTmp = () => {
  downLoadVarTmp({
    tpId: tpId.value + "" || ""
  }).then((res: any) => {
    // console.log(res)
    const blob = new Blob([res.data], {
      type: "application/xlsx;charset=utf-8"
    })
    // console.log(res)
    const downloadElement = document.createElement("a")
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = "变量模板.xlsx"
    document.body.appendChild(downloadElement)
    downloadElement.click()
    window.URL.revokeObjectURL(href)
  })
}

// 发送短信提交按钮
const btnflag = ref<boolean>(false)
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      btnflag.value = true
      if (sendType.value === "1") {
        sendMsgNum({
          phone: ruleForm.phone,
          msg: ruleForm.content,
          sign: ruleForm.content?.match(/【(.*?)】/)[0],
          sendtime: ruleForm.sendtime,
          tpId: tpId.value
        })
          .then((res: any) => {
            if (res.code == 200) {
              ElMessage.success("发送成功")
              ruleFormRef.value?.clearValidate()
              formEl.resetFields()
            }
          })
          .finally(() => {
            btnflag.value = false
          })
      } else {
        const formData = new FormData()
        formData.append("tpId", tpId.value)
        formData.append("sign", ruleForm.content?.match(/【(.*?)】/)[0])
        formData.append("msg", ruleForm.content)
        formData.append("sendtime", ruleForm.sendtime)
        formData.append("file", fileList1.value[0].raw)
        sendMsgFile(formData)
          .then((res: any) => {
            if (res.code == 200) {
              ElMessage.success("发送成功")
              ruleFormRef.value?.clearValidate()
              formEl.resetFields()
              fileList1.value = []
            }
          })
          .finally(() => {
            btnflag.value = false
          })
      }

      // ruleFormRef.value?.clearValidate()
      // formEl.resetFields()
    } else {
      console.log("error submit!", fields)
    }
  })
}
</script>

<template>
  <div class="app-container">
    <el-card>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
            status-icon
          >
            <el-form-item label="短信类型" prop="msgType">
              <el-select v-model="ruleForm.msgType" placeholder="选择类型" @change="tmpTypeChange">
                <el-option label="模板发送" value="temp" />
                <el-option label="自定义发送" value="custom" />
              </el-select>
            </el-form-item>
            <el-form-item label="选择签名" prop="msgSign" v-if="ruleForm.msgType === 'custom'">
              <el-select style="width: 100%" v-model="ruleForm.msgSign" clearable filterable placeholder="请选择签名">
                <el-option v-for="item in singnList" :key="item.id" :label="item.sign" :value="item.sign" />
              </el-select>
            </el-form-item>
            <el-form-item label="选择模板" prop="msgTmp" v-if="ruleForm.msgType === 'temp'">
              <el-button type="primary" :icon="Switch" @click="handleChangeTmp">选择模板</el-button>
            </el-form-item>
            <el-form-item label="短信内容" prop="content">
              <el-input
                v-model="ruleForm.content"
                type="textarea"
                placeholder="请输入短信内容,最多800个字"
                maxlength="800"
                show-word-limit
                rows="6"
                :disabled="ruleForm.msgType === 'temp'"
              />
              <el-checkbox v-model="checked1" label="拒收请回复R" size="large" />
              <p style="width: 100%; margin: 0; margin-top: 10px; line-height: 1em; font-size: 14px">
                <span>
                  已输入 {{ ruleForm.content.length }} 字，最多800
                  字（含签名）,70字内（含70字）计一条，超过70字，按67字/条计费
                </span>
                <el-link type="primary" v-if="ruleForm.msgType === 'temp'" @click="handleUploadTmp"
                  >下载变量模板</el-link
                >
              </p>
            </el-form-item>
            <el-form-item label="预定发送时间" prop="sendtime">
              <el-date-picker
                v-model="ruleForm.sendtime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetime"
                placeholder="若为空，表示立即发送"
              />
            </el-form-item>
            <el-form-item prop="sendType" label="发送方式">
              <el-radio-group v-model="sendType" class="ml-4" @change="sendTypeChange">
                <el-radio label="1" size="large" v-if="ruleForm.content.indexOf('{') == -1">号码发送</el-radio>
                <el-radio label="2" size="large">文件发送</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone" v-if="sendType === '1'">
              <!-- oninput="value=value.replace(/[^0-9,]/g,'')" 只能输入数字和英文逗号 -->
              <el-input
                oninput="value=value.replace(/[^0-9,]/g,'')"
                v-model="ruleForm.phone"
                type="textarea"
                rows="6"
                placeholder="手动最多输入2000个手机号码，号码之间用英文逗号隔开,最后一组号码后禁止添加逗号"
              />
            </el-form-item>
            <el-form-item v-if="sendType === '2'">
              <el-upload
                class="upload-demo"
                style="width: 100%"
                :on-change="handleChageFile"
                :on-remove="handleDelFile"
                :limit="1"
                drag
                :auto-upload="false"
                :file-list="fileList1"
                multiple
                accept=".xlsx,.xls,.txt"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖到此处， <em>或点击上传</em></div>
                <template #tip>
                  <div class="el-upload__tip">
                    格式要求：支持.xlsx .xls.txt 等格式,<br />文件内容手机号码数最大2000个(如上传文件将会自动清除下面手动填写的手机号码)
                    <br />TXT格式：只支持一行一个号码。
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button :disabled="btnflag" type="primary" @click="submitForm(ruleFormRef)"> 发送信息 </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12" style="text-align: center">
          <div class="send-mobel-box">
            <img src="https://fx.yunyoutongxin.com/image/sendMob.png" alt="" />
            <p
              style="
                width: 80px;
                position: absolute;
                top: 122px;
                left: 50%;
                margin-left: -40px;
                font-size: 12px;
                color: rgb(102, 102, 102);
                box-sizing: initial;
              "
            >
              短信
            </p>
            <div class="sms-content-exhibition el-scrollbar">
              <div class="el-scrollbar__wrap" style="margin-bottom: -17px; margin-right: -17px">
                <div class="el-scrollbar__view">
                  <div
                    style="
                      width: 178px;
                      text-align: left;
                      overflow-wrap: break-word;
                      word-break: break-all;
                      white-space: pre-wrap;
                    "
                  >
                    {{ ruleForm.content }}
                  </div>
                </div>
              </div>
              <div class="el-scrollbar__bar is-horizontal">
                <div class="el-scrollbar__thumb" style="transform: translateX(0%)" />
              </div>
              <div class="el-scrollbar__bar is-vertical">
                <div class="el-scrollbar__thumb" style="transform: translateY(0%)" />
              </div>
            </div>
            <div style="width: 80px; position: absolute; left: 72px; top: 277px">
              <span
                style="
                  width: 17px;
                  height: 20px;
                  position: absolute;
                  left: -50px;
                  top: 50px;
                  border-radius: 100% 0px 80%;
                  background: rgb(226, 226, 226);
                "
              /><span
                style="
                  width: 17px;
                  height: 20px;
                  position: absolute;
                  left: -58px;
                  top: 50px;
                  border-radius: 100% 0px;
                  background: rgb(255, 255, 255);
                "
              />
            </div>
          </div>
          <div style="font-size: 12px; text-align: center">
            <div>
              当前发送内容
              <span style="color: rgb(210, 7, 7)">{{ ruleForm.content.length }}</span>
              个字，预计发送条数约为
              <span style="color: rgb(210, 7, 7)">{{
                ruleForm.content.length / 70 <= 1 && ruleForm.content.length / 70 > 0
                  ? 1
                  : Math.ceil(ruleForm.content.length / 67)
              }}</span>
              条短信
            </div>
            <div style="color: rgb(210, 7, 7)">(实际发送时，如有模板变量会影响计费条数，请注意关注)</div>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog v-model="dialogVisibleTmp">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="temName" label="模板">
          <el-input v-model.trim="searchData.temName" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-scrollbar height="600px">
        <el-table :data="tableTmp">
          <el-table-column prop="temId" label="模板ID" align="center" />
          <el-table-column prop="createTime" label="申请时间" align="center">
            <template #default="scope">
              <text v-if="scope.row.createTime !== null"> {{ formatDateTime(scope.row.createTime) }}</text>
            </template>
          </el-table-column>
          <el-table-column prop="temName" label="模板名称" align="center" />
          <el-table-column prop="temContent" label="模板内容" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}
.send-mobel-box {
  width: 260px;
  display: inline-block;
  overflow: hidden;
  position: relative;
  margin-bottom: 35px;

  img {
    width: 100%;
  }
}
.sms-content-exhibition {
  width: 200px;
  height: 40%;
  border-radius: 10px;
  position: absolute;
  padding: 8px 9px;
  background: #e2e2e2;
  top: 160px;
  left: 31px;
  font-size: 12px;
  line-height: 18px;
  color: #000;
  overflow: hidden;
  .el-scrollbar__wrap {
    overflow-x: hidden;
    margin-right: -27px !important;
  }
}
</style>
